<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-col :span="6">
            <el-select v-model="status" placeholder="选择订单状态">
              <el-option label="全部" value="" />
              <el-option label="已完成" value="completed" />
              <el-option label="待处理" value="pending" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="kwInput"
              placeholder="输入 任意字符 进行筛选"
              class="input-with-select"
              clearable
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          show-summary
          :summary-method="getSummaries"
          :default-sort="{prop: 'transaction_date', order: 'descending'}"
          style="width: 100%"
        >
          <el-table-column align="center" label="订单编号" prop="crmorder_order_no" width="80" />
          <el-table-column align="center" label="交易日期" prop="transaction_date" width="120" />
          <el-table-column align="center" label="交易类型" prop="transaction_type" width="120" />
          <el-table-column align="center" label="金额" prop="amount" width="100">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.is_income ? 'green' : 'red' }">
                {{ scope.row.is_income ? '+' : '-' }}{{ scope.row.amount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="货币" prop="currency" width="80" />
          <el-table-column align="center" label="收支类型" prop="is_income" width="80">
            <template slot-scope="scope">
              {{ scope.row.is_income ? '收入' : '支出' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="类别" prop="category" width="100" />
          <el-table-column align="center" label="状态" prop="status" width="100">
            <template slot-scope="scope">
              {{ scope.row.status === 'completed' ? '已完成' : scope.row.status === 'pending' ? '待处理' : '已取消' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="供应商/客户" prop="vendor_or_customer" width="150" />
          <el-table-column align="center" label="是否已对账" prop="is_reconciled" width="100">
            <template slot-scope="scope">
              {{ scope.row.is_reconciled ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="单号" prop="reference_number" width="100" />
          <el-table-column align="center" label="附件" prop="notes">
            <template slot-scope="scope">
              <div class="file-list">
                <div v-for="(item, index) in scope.row.crmfiles" :key="index" class="file-item">
                  <el-image
                    v-if="item.content_type.indexOf('image') !== -1"
                    :src="item.url"
                    :preview-src-list="[item.url]"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('pdf') !== -1"
                    icon-class="pdf"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('xlsx') !== -1"
                    icon-class="xlsx"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('xls') !== -1"
                    icon-class="xls"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('zip') !== -1"
                    icon-class="zip"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else
                    icon-class="document"
                    class="file-icon"
                  />
                  <div class="file-name">{{ item.filename }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEditFromTable(scope.row)">编辑</el-button>
              <el-button type="text" size="small" title="联系管理员删除" style="color: #909399;" @click="handleDeleteFromTable(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleSizeChange"
        />
      </el-main>
      <el-drawer
        :title="temp.crm_order_no + '订单财务记录'"
        :visible.sync="childFormVisible"
        :wrapper-closable="false"
        append-to-body
        size="60%"
        class="mt-dialog"
      >
        <div style="margin: 20px;">
          <el-form :model="temp" :rules="rules" label-position="right" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="交易日期" prop="transaction_date">
                  <el-date-picker v-model="temp.transaction_date" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="交易类型" prop="transaction_type">
                  <el-select v-model="temp.transaction_type" placeholder="请选择交易类型">
                    <el-option
                      v-for="item in finance_transactiontypes"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="金额" prop="amount">
                  <el-input-number v-model="temp.amount" :precision="2" :step="0.1" />
                </el-form-item>
                <el-form-item label="货币" prop="currency">
                  <el-input v-model="temp.currency" />
                </el-form-item>
                <el-form-item label="是否收入" prop="is_income">
                  <el-switch v-model="temp.is_income" />
                </el-form-item>
                <el-form-item label="财务类别" prop="category">
                  <el-select v-model="temp.category" placeholder="请选择类别">
                    <el-option
                      v-for="item in finance_categories"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="单号" prop="reference_number">
                  <el-input v-model="temp.reference_number" />
                </el-form-item>
                <el-form-item label="支付方式" prop="payment_method">
                  <el-input v-model="temp.payment_method" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="temp.status" placeholder="请选择状态">
                    <el-option label="已完成" value="completed" />
                    <el-option label="待处理" value="pending" />
                    <el-option label="已取消" value="cancelled" />
                  </el-select>
                </el-form-item>
                <el-form-item label="供应商/客户" prop="vendor_or_customer">
                  <el-input v-model="temp.vendor_or_customer" />
                </el-form-item>
                <el-form-item label="预期付款日期" prop="expected_payment_date">
                  <el-date-picker v-model="temp.expected_payment_date" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="实际付款日期" prop="actual_payment_date">
                  <el-date-picker v-model="temp.actual_payment_date" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="是否已对账" prop="is_reconciled">
                  <el-switch v-model="temp.is_reconciled" />
                </el-form-item>
                <el-form-item label="对账日期" prop="reconciliation_date">
                  <el-date-picker v-model="temp.reconciliation_date" type="date" placeholder="选择日期" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="notes">
              <el-input v-model="temp.notes" type="textarea" />
            </el-form-item>
            <el-form-item label="关联文件" prop="crmfiles">
              <div class="file-list">
                <div v-for="(item, index) in temp.crmfiles" :key="index" class="file-item">
                  <el-image
                    v-if="item.content_type.indexOf('image') !== -1"
                    :src="item.url"
                    :preview-src-list="[item.url]"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('pdf') !== -1"
                    icon-class="pdf"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('xlsx') !== -1"
                    icon-class="xlsx"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('xls') !== -1"
                    icon-class="xls"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename.indexOf('zip') !== -1"
                    icon-class="zip"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else
                    icon-class="document"
                    class="file-icon"
                  />
                  <div class="file-name">{{ item.filename }}</div>
                </div>
              </div>
              <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
            </el-form-item>
          </el-form>
          <el-row type="flex" justify="center">
            <el-button @click="childFormVisible = false;editloading=false;">取 消</el-button>
            <el-button type="primary" :loading="editloading" @click="confirm">确 定</el-button>
          </el-row>
        </div>
      </el-drawer>
    </el-container>
  </div>
</template>

<script>
import { Get, Post, Put } from '@/api/crm/crmorderfinance'
import { ShowProjectAttr } from '@/api/erp/elicink/project'
import qs from 'qs'
import Crmfilesmanager from '../../components/crmfilesmanager'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Crmfinance',
  components: { Crmfilesmanager },
  data() {
    return {
      crm_order_id: '',
      childFormVisible: false,
      listLoading: false,
      editloading: false,
      data: [],
      rules: {
        transaction_date: [{ required: true, message: '请选择交易日期', trigger: 'change' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
        // 添加其他必要的验证规则
      },
      action: 'create',
      temp: this.initTemp(),
      finance_categories: [],
      finance_transactiontypes: [],
      kwInput: '',
      status: '',
      order_by: '',
      order_desc: orderMapper[0],
      pagesize: 100,
      page: 1,
      total: 0,
      fileList: []
    }
  },
  created() {
    this.handleGetFinanceCategoy()
    this.handleGetFinanceTransactionTypes()
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1 // 切换每页显示数量时重置为第一页
      this.getList()
    },
    handleSearch() {
      this.page = 1
      this.getList()
    },
    initTemp() {
      return {
        crm_order_id: '',
        crm_order_no: '',
        transaction_date: new Date(),
        transaction_type: '产品成本支出',
        amount: 0,
        currency: 'CNY',
        is_income: false,
        category: '物流费用',
        payment_method: '',
        status: 'pending',
        reference_number: '',
        notes: '',
        vendor_or_customer: '',
        expected_payment_date: null,
        actual_payment_date: null,
        is_reconciled: false,
        reconciliation_date: null,
        attachment: null,
        crmfiles: []
      }
    },
    handleGetFinanceCategoy() {
      ShowProjectAttr(null, qs.stringify({ name: '财务费用类型' })).then(response => {
        this.finance_categories = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleGetFinanceTransactionTypes() {
      ShowProjectAttr(null, qs.stringify({ name: '财务交易类型' })).then(response => {
        this.finance_transactiontypes = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleInsertFile(item) {
      console.log(item)
      if (!this.temp.crmfiles) {
        this.temp.crmfiles = []
      }
      if (this.temp.crmfiles.findIndex(file => file.id === item.id) === -1) {
        this.temp.crmfiles.push(item)
      }
    },
    handleEditFromTable(row) {
      this.temp = { ...this.initTemp(), ...row }
      this.action = 'edit'
      this.childFormVisible = true
    },
    handleDeleteFromTable(row) {
      // 防止财务信息丢失，不允许直接删除，需要联系管理员
      this.$alert(
        `财务记录 ID：${row.id}\n\n为防止重要财务信息丢失，请联系系统管理员进行删除操作。\n\n请将此ID提供给管理员以便处理。`,
        '删除提示',
        {
          confirmButtonText: '我知道了',
          type: 'warning',
          showClose: false
        }
      )
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (column.property === 'amount') {
          const income = data.filter(item => item.is_income)
            .reduce((prev, curr) => prev + parseFloat(curr.amount || 0), 0)
          const expense = data.filter(item => !item.is_income)
            .reduce((prev, curr) => prev + parseFloat(curr.amount || 0), 0)
          sums[index] = `收入: ${income.toFixed(2)}\n支出: ${expense.toFixed(2)}\n净额: ${(income - expense).toFixed(2)}`
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    handleShowEdit() {
      this.temp = this.initTemp()
      this.childFormVisible = true
      this.action = 'create'
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        status: this.status,
        page: this.page,
        crm_order_id: this.crm_order_id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    confirm() {
      this.editloading = true
      const action = this.action === 'create' ? Post
        : (data) => Put(this.temp.id, data)

      action(this.temp).then(() => {
        this.childFormVisible = false
        this.editloading = false
        this.$emit('reload')
        this.notify(this.action === 'edit' ? '修改成功' : '添加成功')
        this.getList()
      }).catch(err => {
        console.log(err)
        this.editloading = false
      })
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    notify(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000
      })
    },
    // 文件上传相关方法
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>

<style scoped>
.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 调整图标之间的间距 */
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px; /* 调整每个文件项的宽度 */
}

.file-icon {
  height: 80px;
  width: 80px;
}

.file-name {
  margin-top: 5px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}
.mt-dialog >>> span.el-dialog__title {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
}
</style>
